package com.zhongfu.emapp.business.base.activity

import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import com.blankj.utilcode.util.KeyboardUtils
import com.zf.zfed.audit.ui.CustomKeyViewModel

/**
 * 活动activity的共同业务逻辑类，便于后期若有共同业务的提取
 */
abstract class BaseLogicActivity : ComponentActivity() {
    /**
     * 自定义物理按键
     */
    val customKeyboardVM: CustomKeyViewModel by viewModels()

    /**
     * 物理按键按下
     *
     * @param keyCode
     * @param event
     * @return
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        customKeyboardVM.onKeyDown(keyCode, event)
        return true
    }

    /**
     * 物理按键抬起
     *
     * @param keyCode
     * @param event
     * @return
     */
    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        customKeyboardVM.onKeyUp(keyCode, event)
        return true
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (MotionEvent.ACTION_DOWN == ev?.action) {
            val v = currentFocus
            if (isShouldHideKeyboard(v, ev)) {
                v?.let {
                    KeyboardUtils.hideSoftInput(it)
                }
                KeyboardUtils.hideSoftInput(this)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v is EditText) {
            val l = intArrayOf(0,0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.height
            val right = left + v.width
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }
}